package com.loong.common.paasoo.utils;


import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 无限云 短信供应商
 * 短信http接口的java代码调用示例
 * 基于Apache HttpClient 4.X
 */
public class PaaSooSmsApiUtil {

	/**
	 * 0 - success：成功
	 * 2 - Missing params：缺少必要参数
	 * 4 - Invalid credentials：Key或Secret错误
	 * 5 - Unauthorized IP：IP限制
	 * 6 - Invalid phone number：号码格式错误
	 * 7 - Invalid sender id：from参数格式错误
	 * 9 - Quota exceeded：欠费或信用额度不足
	 */

	    //编码格式。发送编码格式统一用UTF-8
	    private static String ENCODING = "UTF-8";
	    //短信发送url
	    private static String URI_GET_SEND_SMS = "https://api.paasoo.cn/json";
	    //发送记录查询url
	    private static String URI_GET_SEND_RECORD = "https://api.paasoo.cn/dlr";
	    //余额查询url
	    private static String URI_GET_USER_BALANCE = "https://api.paasoo.cn/balance";
	    //号码格式验证url
	    private static String URI_GET_VALID_NUMBER = "https://api.paasoo.com/lookup";

	    public static void main(String[] args) throws Exception {
	        //参数
	        String key = "ftutclut";
	        String secret = "6jTDMMkEFtne";
	        String from = "loong";
	        String to = "639212703992";
	        String text = "[Loong Delivery] Your verification code is {0}.";
	        String messageid = "********";
		 	String countryCode = "63";
	        String nationalNumber = "9212703992";

	        /**************** 查短信发送信息调用示例 *****************/
	      //  System.out.println(PaaSooSmsApiUtil.sendSms(URI_GET_SEND_SMS,key, secret, from, to, text));

	        /**************** 查发送记录信息调用示例 *****************/
	     //   System.out.println(PaaSooSmsApiUtil.getSentRecord(key, secret, messageid));

	        /**************** 查余额信息调用示例 *****************/
	      //  System.out.println(PaaSooSmsApiUtil.getUserBalance(key, secret));

	        /**************** 号码格式验证调用示例 *****************/
	        System.out.println(PaaSooSmsApiUtil.getValidNumber(key, secret, countryCode, nationalNumber));
	    }

	    /**
	     *短信发送
	     * @param url   短信发送url
	     * @param key    API帐号
	     * @param secret API密码
	     * @param from   SenderID
	     * @param to     发送目标号码
	     * @param text   发送内容
	     * @return json  格式字符串
	     * @throws Exception
	     */

	    public static String sendSms(String url, String key, String secret, String from, String to, String text) throws Exception {
	        Map<String, String> params = new HashMap<String, String>();
	        params.put("key", key);
	        params.put("secret", secret);
	        params.put("from", from);
	        params.put("to", to);
	        params.put("text", text);
	        return get(url, params);
	    }

	    /**
	     * 发送记录查询
	     * @param key       API帐号
	     * @param secret    API密码
	     * @param messageId 发送记录消息ID
	     * @return
	     * @throws Exception
	     */
	    public static String getSentRecord(String key, String secret, String messageId) throws Exception {
	        Map<String, String> params = new HashMap<String, String>();
	        params.put("key", key);
	        params.put("secret", secret);
	        params.put("messageid", messageId);
	        return get(URI_GET_SEND_RECORD, params);
	    }

	    /**
	     * 余额查询
	     * @param key    API帐号
	     * @param secret API密码
	     * @return
	     * @throws Exception
	     */
	    public static String getUserBalance(String key, String secret) throws Exception {
	        Map<String, String> params = new HashMap<String, String>();
	        params.put("key", key);
	        params.put("secret", secret);
	        return get(URI_GET_USER_BALANCE, params);
	    }

	    /**
	     *号码格式验证
	     *
	     * @param key            API帐号
	     * @param secret         API密码
	     * @param countryCode    待验证手机号码所在国家区号
	     * @param nationalNumber 待验证的手机号码，不含国家区号
	     * @return
	     * @throws Exception
	     */
	    public static String getValidNumber(String key, String secret, String countryCode, String nationalNumber){
	        Map<String, String> params = new HashMap<String, String>();
	        params.put("key", key);
	        params.put("secret", secret);
	        params.put("number", countryCode+nationalNumber);
	        return get(URI_GET_VALID_NUMBER, params);
	    }


	    /**
	     * 基于HttpClient 4.X的通用GET方法
	     * @param url       提交的URL
	     * @param paramsMap 提交<参数，值>Map
	     * @return          提交响应
	     */
	    public static String get(String url, Map<String, String> paramsMap){
	        CloseableHttpClient httpClient = HttpClients.createDefault();
	        CloseableHttpResponse response = null;
	        InputStream is = null;
	        try {
	            List<NameValuePair> params = new ArrayList<NameValuePair>();
	            for (Map.Entry<String, String> param : paramsMap.entrySet()) {
	                NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
	                params.add(pair);
	            }
	            String str = EntityUtils.toString(new UrlEncodedFormEntity(params, ENCODING));
	            HttpGet httpGet = new HttpGet(url + "?" + str);
	            response = httpClient.execute(httpGet);
	            HttpEntity entity = response.getEntity();
	            String result = EntityUtils.toString(entity);
	            return result;
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            if (is != null) {
	                try {
	                    is.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	            if (response != null) {
	                try {
	                    response.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	            if (httpClient != null) {
	                try {
	                    httpClient.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	        return null;
	    }
	}
